import Vuex from 'vuex'
import user from './modules/user'
import app from './modules/app'
import { getUserInfo } from '../API/user'
import { token } from '../util/auth'
const actions = {
  async nuxtServerInit({ commit }, { params, route, isServer, req }) {
    const __initData = []
    let cookie = ''
    let arrs = req.headers.cookie ? req.headers.cookie.split(';') : []
    arrs.forEach(item => {
      if (item.split('=')[0] === token) {
        cookie = item.split('=')[1]
      }
    })
    if (cookie) {
      let user = await getUserInfo(cookie)
      __initData.push(commit('SET_USER', user))
    } else {
      __initData.push(commit('SET_USER', {}))
    }

    return Promise.all(__initData)
  }
}

const createStore = () => {
  return new Vuex.Store({
    modules: {
      user,
      app
    },
    actions: actions
  })
}

export default createStore
